#define  _CRT_SECURE_NO_WARNINGS
#include "SLTList.h"

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	assert(node);
	node->data = x;
	node->next = NULL;

	return node;
}

void SLTPrint(SLTNode* phead)
{

	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (NULL == *pphead)
	{
		*pphead = newnode;
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;

	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (NULL == *pphead)
	{
		*pphead = newnode;
	}
	else
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	SLTNode* pre = NULL;
	
	if (NULL == pcur->next)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		while (pcur->next)
		{
			pre = pcur;
			pcur = pcur->next;
		}
		free(pre->next);
		pre->next = NULL;
	}
}

void SLTPopFront(SLTNode** pphead)
{
	assert(*pphead && pphead);
	SLTNode* tmp = *pphead;
	*pphead = (*pphead)->next;
	free(tmp);
	tmp = NULL;
}

SLTNode* SLTNodeFind(SLTNode** pphead, SLTDataType x)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		if (x == pcur->data)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void SLTInvert(SLTNode** pphead, SLTNode* lo, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (lo == *pphead)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next != lo)
		{
			pcur = pcur->next;
		}
		newnode->next = lo;
		pcur->next = newnode;
	}
}

void SLTInvertafter(SLTNode** pphead, SLTNode* lo, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	SLTNode* pcur = *pphead;
	while (pcur != lo)
	{
		pcur = pcur->next;
	}
	newnode->next = pcur->next;
	pcur->next = newnode;
}

void SLTErase(SLTNode** pphead, SLTNode* lo)
{
	assert(pphead && *pphead && lo);

	if (lo == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* pcur = *pphead;
		SLTNode* pre = NULL;
		while (pcur != lo)
		{
			pre = pcur;
			pcur = pcur->next;
		}
		pre->next = pcur->next;
		free(pcur);
		pcur = NULL;
	}

}

void SLTEraseAfter(SLTNode* lo)
{
	assert(lo&& lo->next);
	SLTNode* tmp = lo->next->next;
	free(lo->next);
	lo->next = tmp;
}

void SLTDestroy(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		pcur = pcur->next;
		free(*pphead);
		*pphead = pcur;
	}

}